<template>
  <div class="app-container">

    <el-row>
      <el-col :span="6" class="mb5" v-if="queryParams.inStore == '1'">
        <el-radio-group v-model="queryParams.isAck" @change="radioChange">
          <el-radio-button v-for="tab in tabs" :label="tab.label" >
            <el-badge :value="tab.badge" class="item">
              {{tab.name}}
            </el-badge>
          </el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="18" class="mb5">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item prop="taskNo">
            <el-input v-model="queryParams.taskNo" placeholder="处置编号" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item prop="dealNo">
            <el-input v-model="queryParams.dealNo" placeholder="物品编号" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="dealList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="index" width="55" align="center" fixed="left" />
      <el-table-column label="处置编号" prop="dealNo" align="center" width="240" fixed="left">
        <!-- <template slot-scope="scope">
          <el-link type="primary" @click="handleInfo(scope.row)">{{scope.row.dealNo}}</el-link>
        </template> -->
      </el-table-column>
      <el-table-column label="物品名称" prop="proName" min-width="200" v-if="queryParams.inStore == '1'"/>
      <el-table-column label="物品名称" prop="dealName" min-width="200" v-if="queryParams.inStore == '0'"/>
      <el-table-column label="扣押单位" prop="detainUnit" min-width="260" v-if="queryParams.inStore == '0'"/>
      <el-table-column label="保管场所" prop="locatorName" min-width="300" v-if="queryParams.inStore == '1'"/>
      <el-table-column label="处置单位" prop="handleUnitName" min-width="260" v-if="queryParams.inStore == '1'">
        <template slot-scope="scope">
          {{scope.row.handleUnitName?scope.row.handleUnitName:scope.row.deptName}}
        </template>
      </el-table-column>
      <el-table-column label="协助单位" prop="helpUnitName" min-width="260" v-if="queryParams.inStore == '1'"/>
      <!-- <el-table-column label="裁决单位" prop="officeName" min-width="260" v-if="queryParams.inStore == '1'"/> -->
      <el-table-column label="裁决单位" prop="judgeUnit" min-width="260"/>
      <el-table-column label="裁决时间" prop="judgeTime" min-width="160"/>
      <el-table-column label="处置人"  align="center" prop="nickName" width="120" v-if="queryParams.inStore == '1'"/>
      <el-table-column label="处置意见" align="center" prop="dealType" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.deal_type" :value="scope.row.dealType" />
        </template>
      </el-table-column>
      <el-table-column label="属性认定" align="center" prop="believe" width="150" v-if="queryParams.inStore == '1'">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.deal_believe" :value="scope.row.believe" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center"  width="80" v-if="queryParams.inStore == '1'">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.deal_validate" :value="scope.row.isAck" />
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="memo" min-width="280" v-if="queryParams.inStore == '1'"/>
      <el-table-column label="文书" prop="wsPdf" width="220" fixed="right">
         <template slot-scope="scope">
           <template v-for="item in scope.row.pdfList">
             <!-- <el-link type="primary" target="_blank" :href="getPdfUrl(item)">{{getPdfName(item)}}</el-link> -->
             <el-link  type="primary" target="_blank" :href="getPdfUrl(item)">
              <el-tooltip class="item" effect="dark" :content="getPdfName(item)" placement="top-start">
                   <el-button size="mini" type="text">{{getPdfName(item) && getPdfName(item).length >20 ? getPdfName(item).substring(0,20)+'...' : getPdfName(item)}}</el-button>
                 </el-tooltip>
             </el-link>
           </template>
         </template>
       </el-table-column>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">

        </template>
      </el-table-column> -->

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改处置对话框 -->

    <el-drawer :visible.sync="open" size="30%">
      <div class="mainDiv">
        <el-container class="main_container">
          <el-main>

          </el-main>
          <el-footer class="footerDivClass">
            <el-button @click="cancelInfo">返 回</el-button>
          </el-footer>
        </el-container>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import {
    listDeal,
    getDeal,
    delDeal,
    addDeal,
    updateDeal
  } from "@/api/wms/deal";
  import {
    listStore,
    storeTreeselect
  } from "@/api/wms/store";
  import {
    storeAreas
  } from "@/api/wms/storeArea";
  import {
    locatores
  } from "@/api/wms/locator";
  import {
    treeselect
  } from "@/api/system/dept";
  import {
    listUser
  } from "@/api/system/user"
  import {listOperatorLog} from "@/api/oms/operatorLog"
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import selectProperty from "@/components/SelectProperty/index.vue";
  export default {
    name: "Deal",
    dicts: ['wms_deal_status', 'sys_del_flag', 'wms_deal_type','deal_type','wms_pick_task_status','deal_check_status','deal_validate','deal_believe'],
    components: {
      Treeselect,
      selectProperty
    },
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 处置表格数据
        dealList: [],
        storeOptions: [],
        userOptions: [],
        storeTree: [],
        storeName: undefined,
        deptOptions: [],
        storeAreaOptions: [],
        storeAreas: [],
        locatorOptions: [],
        locators: [],
        logOptions:[],
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        update:false,
        checkShow:false,
        isInfo:false,
        // 交接信息时间范围
        daterangeCreateTime: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          taskId: undefined,
          dealNo: undefined,
          deptId: undefined,
          operator: undefined,
          status: undefined,
          handId: undefined,
          createTime: undefined,
          createBy: undefined,
          isAck:undefined,
          delFlag: "0",
          source:'1',
          inStore:undefined,
          believe:undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          // taskId: [{
          //   required: true,
          //   message: "任务ID不能为空",
          //   trigger: "blur"
          // }],
          // dealNo: [{
          //   required: true,
          //   message: "处置单编号不能为空",
          //   trigger: "blur"
          // }],
          // deptId: [{
          //   required: true,
          //   message: "部门ID不能为空",
          //   trigger: "blur"
          // }],
          // operator: [{
          //   required: true,
          //   message: "处置人ID不能为空",
          //   trigger: "blur"
          // }],
        },
        tabs:[
          {label:undefined,name:'全部',badge:undefined,value:undefined},
          {label:'0',name:'待确认',badge:undefined,value:'0'},
          {label:'1',name:'已确认',badge:undefined,value:'1'}
        ],
        showTabs:true,
        registerInfo:{}
      };
    },
    watch: {
      storeName(val) {
        this.$refs.tree.filter(val);
      },
      'queryParams.deptId': {
        handler(newVal, oldVal) {
          this.deptChange();
        },
        deep: true,
        immediate: true
      }
    },
    mounted() {

    },
    created() {
      const inStore = this.$router.currentRoute.query.inStore;
      console.info("inStore::",inStore);
      this.queryParams.believe = inStore;
      this.queryParams.inStore = inStore;
      this.getList();
      this.getStoreTreeselect();
      this.getTreeselect();
      this.getUsers();
      this.getAreaAndLocators();
    },
    methods: {
      radioChange(e){
        this.tabs.forEach(item=>{
            if(item.value == e){
              this.queryParams.isAck = item.value;
            }
        })
        this.getList();
      },
      /** 查询处置列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        }
        listDeal(this.queryParams).then(response => {
          this.dealList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.tabs.forEach((item)=>{
          	if(item.value == this.queryParams.isAck){
          		item.badge = this.total;
          	}else{
          		item.badge = undefined;
          	}
          })
        });

      },
      getLogs(id){
        listOperatorLog({"objid":id,"logType":"wms"}).then(response=>{
          this.logOptions = response.rows;
        })
      },
      /** 查询分类下拉树结构 */
      getStoreTreeselect() {
        storeTreeselect().then(response => {
          this.storeOptions = response.data;
        });
      },
      getAreaAndLocators() {
        storeAreas({
          "storeId": this.queryParams.storeId
        }).then(response => {
          this.storeAreaOptions = response.data;
        });
        locatores({
          "storeId": this.queryParams.storeId
        }).then(response => {
          this.locatorOptions = response.data;
        });
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      getUsers() {
        listUser({
          'userType': 'sys_user',
          'deptId': this.queryParams.deptId
        }).then(response => {
          this.userOptions = response.rows
        })
      },
      deptChange() {
        this.getUsers()
        this.getList();
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.storeId = data.id;
        this.handleQuery();
        this.getAreaAndLocators()
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        // this.reset();
      },
      cancelCheck(){
        this.checkShow = false;
      },
      cancelInfo(){
        this.isInfo = false;
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          taskId: undefined,
          dealNo: undefined,
          deptId: undefined,
          operator: undefined,
          status: undefined,
          memo: undefined,
          pics: undefined,
          handId: undefined,
          createTime: undefined,
          createBy: undefined,
          updateTime: undefined,
          updateBy: undefined,
          delFlag: undefined,
          items: []
        };
        this.resetForm("form");
      },
      addDtl() {
        // let data = {
        //   id: undefined,
        //   dealId: undefined,
        //   pno: undefined,
        //   name: undefined,
        //   nums: undefined,
        //   dealType: undefined,
        //   pics: undefined,
        //   status: undefined,
        //   createTime: undefined,
        //   createBy: undefined,
        //   updateTime: undefined,
        //   updateBy: undefined,
        //   storeId: undefined,
        //   locatorId: undefined,
        //   areaId: undefined,
        //   delFlag: '0'
        // }
        // this.form.items.push(data)
        this.$refs.elDrawer.open()
      },
      dtlDel(scope) {
        let index = scope.$index;
        if (this.form.items[index].id && this.form.items[index].id != '') {
          this.form.items[index].delFlag = '2';
        } else {
          this.form.items.splice(index, 1)
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeCreateTime = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加处置";
        this.form.storeId = this.queryParams.storeId;
        this.getAreaAndLocators();
        // this.$router.push({
        //   path: '/wms/dealInfo/add',
        //   query: {
        //     pageNum: this.queryParams.pageNum
        //   }
        // })
      },
      handleInfo(row){
        this.update = true;
        const id = row.id || this.ids
        getDeal(id).then(response => {
          this.form = response.data;
        });
        this.getLogs(row.taskId ? row.taskId:id)
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        // this.loading = true;
        // this.reset();
        // this.getAreaAndLocators();
        // const id = row.id || this.ids
        // getDeal(id).then(response => {
        //   this.loading = false;
        //   this.form = response.data;
        //   this.open = true;
        //   this.title = "修改处置";
        // });
        this.open = true;
        this.title = "修改处置单";
        this.$refs.elDrawer.getList();
      },
      handleCheck(row){
        if(row.nums == 0){
          this.$modal.msgWarning("物品不在库，无法审核！");
        }else{
          const id = row.id || this.ids
          getDeal(id).then(response=>{
            this.form = response.data;
            this.checkShow = true;
          })
        }

      },
      handlePick(row){
        const id = row.id || this.ids;
        this.$router.push({
          path: '/wms/dealInfo/pick/'+row.id,
          query: {
            pageNum: this.queryParams.pageNum
          }
        })
      },
      handleRegister(row){
        this.isInfo = true;
        const id = row.id || this.ids
        getDeal(id).then(response => {
          this.form = response.data;
          this.registerInfo = JSON.parse(response.data.registerInfo);
        });
      },
      handleTask(row){
        const id = row.id || this.ids;
        console.info('id===>',id)
        this.$router.push({
          path: '/oms/dealInfo/addDeal',
          query: {
            pageNum: this.queryParams.pageNum,
            ids:id
          }
        })
      },
      //获取选择后的财务数据
        handleSelected(array){
          array.forEach(item=>{
            item.delFlag = '0'
            item.id=undefined
            this.form.items.push(item)
          })
        },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          // this.form.oss = this.$refs["imageUpload"].pics;
          if (valid) {
            if (this.form.id != null) {
              if(this.form.isCheck == '0'){
                this.$modal.msgWarning("请选择审核状态");
                return false;
              }
              this.buttonLoading = true;
              updateDeal(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.checkShow = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addDeal(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.checkShow = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除处置编号为"' + ids + '"的数据项？').then(() => {
          this.loading = true;
          return delDeal(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('wms/deal/export', {
          ...this.queryParams
        }, `deal_${new Date().getTime()}.xlsx`)
      },
      getPdfName(fileUrl){
          let files = fileUrl.split('/');
          let _names = files[files.length-1];
          let fileName = _names;
          if(_names && _names.indexOf("_") != -1){
            let fileNames = _names.split("_");
            fileName = fileNames[fileNames.length - 1];
          }
          return fileName;
      },
      getPdfUrl(fileUrl){
          let markParams = {
            "text":"三明市安保信息科技有限公司",
            "fontSize":"20",
            "color":"rgba(128,128,128,0.6)",
            "rotate":"330",
            "Place":"middleCenter",
            "Rule":"all",
            "tiling":"false",
            "fontName":"SimSun",
            "distanceX":"10",
            "distanceY":"10"
        }
        let host = location.hostname;
        if(host == '192.168.1.256'){host = host.replace('192.168.1.256','192.168.1.241')}
        if(host == '192.168.1.246'){host = host.replace('192.168.1.246','192.168.1.241')}
        if(host == '10.49.241.156'){host = host.replace('10.49.241.156','10.49.241.151')}
        let origin = location.protocol+'//'+host;
        let url = origin+':8095/reader?file='+fileUrl+'&markParams='+encodeURIComponent(JSON.stringify(markParams));
        return url;
      }
    }
  };
</script>
